var express = require('express');
var router = express.Router();
var login = require("../services/login_service")
var file_service = require("../services/file/file_service")
let multer = require('multer')

var storage = multer.diskStorage({
    destination: function (req, file, cb) {
        cb(null, '../upload/');
    },
    filename: function (req, file, cb) {
        var fileFormat = (file.originalname).split(".");
          cb(null, Date.now() + '-' + Math.random()*100000000000000000000 + "." + fileFormat[fileFormat.length - 1]);
    }
});
var upload = multer({ storage: storage })

let handler = async function (req, res, next) {
	let error = function (status, msg, err) {
		if (err) {
			msg = msg + " 详细错误: " + err.name + " " + err.message;
		}
		err_data = { status: status, msg: msg };
		res.send(err_data);
		console.error(err_data, err);
	}
	let ok = function (result) {
		res.send({ status: 0, msg: "ok", data: result });
	}
	try {
		let token = req.cookies.token;
		let log_info = await login.get_refresh_login_info(token);
		if (log_info instanceof Error) { error(403, "未授权的访问 " + log_info.message); return; }
		console.log("---user info--- " + new Date() + " 上传文件 username:" + log_info.username + " user_id:" + log_info.user_id + " emp_id:" + log_info.emp_id + " ip:" + req.ip)
		let result = await file_service.handle("upload", {file:req.file}, log_info, req, res);
		if (result instanceof Error) {
			error(500, "上传文件发生错误", result);
		}
		else {
			ok(result);
		}
	}
	catch (err) {
		if (err.message == "登录已过期") {
			error(403, "登录已过期", err);
		}
		else {
			error(500, "api出现错误", err);
		}
	}
}

let download_handler = async function (req, res, next) {
	let error = function (status, msg, err) {
		if (err) {
			msg = msg + " 详细错误: " + err.name + " " + err.message;
		}
		
		console.log(msg);
		err_data = { status: status, msg: msg };
		res.send(err_data);
		console.error(err_data, err);
	}
	try {
		let token = req.cookies.token;
		let log_info = await login.get_refresh_login_info(token);
		if (log_info instanceof Error) { error(403, "未授权的访问 " + log_info.message); return; }
		console.log("---user info--- " + new Date() + " 上传文件 username:" + log_info.username + " user_id:" + log_info.user_id + " emp_id:" + log_info.emp_id + " ip:" + req.ip)
		let result = await file_service.handle("download", {guid:req.params.guid}, log_info, req, res);
		if (result instanceof Error) {
			error(500, "下载文件发生错误", result);
		}
	}
	catch (err) {
		if (err.message == "登录已过期") {
			error(403, "登录已过期", err);
		}
		else {
			error(500, "api出现错误", err);
		}
	}
}

/* API. */
router.post('/upload', upload.single('file'), handler);
router.get('/download/:guid', download_handler);

module.exports = router;
